package com.example.demo.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

public class EncryptionTool {
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f'};
    private static final Log logger = LogFactory.getLog(EncryptionTool.class);
    // 加密密钥文字
    private static final String keyStr4DES = "BosupoeHjnhlkey8";
    // 算法名称/加密模式/填充方式    DES共有四种工作模式-->>ECB：电子密码本模式、CBC：加密分组链接模式、CFB：加密反馈模式、OFB：输出反馈模式
    private static final String desType = "DES/ECB/PKCS5Padding";
    // 加密密钥
    private static Key key4DES = null;

    static {
        try {
            key4DES = keyGenerator4DES(keyStr4DES);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成密钥key对象
     *
     * @param KeyStr 密钥字符串
     * @return 密钥对象
     * @throws Exception
     */
    private static SecretKey keyGenerator4DES(String keyStr) throws Exception {
        byte input[] = hexString2Bytes(keyStr);
        DESKeySpec desKey = new DESKeySpec(input);
        // 创建一个密匙工厂，然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        return securekey;
    }

    private static int parse(char c) {
        if (c >= 'a')
            return (c - 'a' + 10) & 0x0f;
        if (c >= 'A')
            return (c - 'A' + 10) & 0x0f;
        return (c - '0') & 0x0f;
    }

    /**
     * 从十六进制字符串到字节数组转换
     *
     * @param hexstr 需要转换的十六进制数据
     * @return
     */
    public static byte[] hexString2Bytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        return b;
    }

    /**
     * 从字节数组到十六进制字符串转换
     *
     * @param bytes 需要转换的字节数组
     * @return
     */
    public static String bytesString2Hex(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }


    /**
     * 使用MD5加密文字
     *
     * @param str
     * @return
     */
    public static String encodeWithMD5(String str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }

        byte[] md5Bytes = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5Bytes = md5.digest(str.getBytes("UTF-8"));
        } catch (Exception e) {
            logger.error("encrypt str with MD5 failed! Str => " + str, e);
            return str;
        }

        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }

    /**
     * encrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static String encryptWithBase64URL(String str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }

        try {
            return Base64.getUrlEncoder().encodeToString(Base64.getEncoder().encode(str.getBytes("UTF-8")));
        } catch (Exception e) {
            return str;
        }
    }

    /**
     * decrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static String decryptWithBase64URL(String str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }

        try {
            return new String(Base64.getDecoder().decode(Base64.getUrlDecoder().decode(str.getBytes("UTF-8"))), "UTF-8");
        } catch (Exception e) {
            return str;
        }
    }


    /**
     * encrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static String encryptWithBase64(String str) {
        try {
            return encryptWithBase64(str.getBytes("UTF-8"));
        } catch (Exception e) {
            return str;
        }
    }

    /**
     * decrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static String decryptWithBase64(String str) {
        if (str == null || "".equals(str)) {
            return null;
        }

        try {
            return new String(Base64.getDecoder().decode(str.getBytes("UTF-8")), "UTF-8");
        } catch (Exception e) {
            return str;
        }
    }

    /**
     * encrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static String encryptWithBase64(byte[] str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }

        try {
            return Base64.getEncoder().encodeToString(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * decrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static String decryptWithBase64(byte[] str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }

        try {
            return new String(Base64.getDecoder().decode(str), "UTF-8");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * encrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static byte[] encryptWithBase64ToByte(byte[] str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }

        try {
            return Base64.getEncoder().encode(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * decrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static byte[] decryptWithBase64ToByte(byte[] str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }

        try {
            return Base64.getDecoder().decode(str);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * encrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static byte[] encryptWithBase64ToByte(String str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }

        try {
            return Base64.getEncoder().encode(str.getBytes("UTF-8"));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * decrypt with base 64
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static byte[] decryptWithBase64ToByte(String str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }

        try {
            return Base64.getMimeDecoder().decode(str.getBytes("UTF-8"));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 使用SHA1加密
     *
     * @param str
     * @return
     * @throws ASDException
     */
    public static String encryptWithSHA1(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(str.getBytes("UTF-8"));
            return bytesString2Hex(messageDigest.digest());
        } catch (Exception e) {
            logger.error("Encode str with SHA1 failed => " + str, e);
            return str;
        }
    }

    /**
     * 使用DES加密文字
     *
     * @param str 待加密数据
     * @return 加密后的数据
     */
    public static String encryptWithDES(String str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }
        try {
            // 实例化Cipher对象，它用于完成实际的加密操作
            Cipher cipher = Cipher.getInstance(desType);
            SecureRandom random = new SecureRandom();
            // 初始化Cipher对象，设置为加密模式
            cipher.init(Cipher.ENCRYPT_MODE, key4DES, random);
            byte[] results = cipher.doFinal(str.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(results);
        } catch (Exception e) {
            e.printStackTrace();
            return str;
        }
    }


    /**
     * 解密数据
     *
     * @param str 待解密数据
     * @return 解密后的数据
     */
    public static String decryptWithDES(String str) {
        if (ValidationUtil.isEmpty(str)) {
            return null;
        }
        try {
            byte[] strBytes = Base64.getDecoder().decode(str);
            Cipher cipher = Cipher.getInstance(desType);
            // 初始化Cipher对象，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, key4DES);
            // 执行解密操作
            return new String(cipher.doFinal(strBytes));
        } catch (Exception e) {
            e.printStackTrace();
            return new String(str);
        }
    }

    /**
     * byte数组转换为二进制字符串,每个字节以","隔开
     *
     * @param bytes 需要转换的二进制数组
     * @return
     */
    public static String conver2HexStr(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            result.append(Long.toString(bytes[i] & 0xff, 2) + ",");
        }
        return result.toString().substring(0, result.length() - 1);
    }

    /**
     * 二进制字符串转换为byte数组,每个字节以","隔开
     *
     * @param hex2Str 需要转换的字符串
     * @return
     */
    public static byte[] conver2HexToByte(String hex2Str) {
        String[] temp = hex2Str.split(",");
        byte[] b = new byte[temp.length];
        for (int i = 0; i < b.length; i++) {
            b[i] = Long.valueOf(temp[i], 2).byteValue();
        }
        return b;
    }

    /**
     * byte数组转换为十六进制的字符串
     *
     * @param bytes 需要转换的字符数组
     * @return
     */
    public static String conver16HexStr(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            if ((bytes[i] & 0xff) < 0x10)
                result.append("0");
            result.append(Long.toString(bytes[i] & 0xff, 16));
        }
        return result.toString().toUpperCase();
    }

    /**
     * 十六进制的字符串转换为byte数组
     *
     * @param hex16Str 需要转换的字符串
     * @return
     */
    public static byte[] conver16HexToByte(String hex16Str) {
        char[] c = hex16Str.toCharArray();
        byte[] b = new byte[c.length / 2];
        for (int i = 0; i < b.length; i++) {
            int pos = i * 2;
            b[i] = (byte) ("0123456789ABCDEF".indexOf(c[pos]) << 4 | "0123456789ABCDEF".indexOf(c[pos + 1]));
        }
        return b;
    }

    public static void main(String[] args) {
        System.out.println(encodeWithMD5("admin_live"));
    }
}

/*
 * $Log: av-env.bat,v $
 */